package servlet;

import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.CareerDev;
import model.Employee;
import model.JobRes;

import org.json.JSONArray;
import org.json.JSONObject;

import dao.ProfileDAO;

/**
 * Servlet implementation class careerDevData
 */
public class careerDevData extends HttpServlet {
	private static final long serialVersionUID = 1L;
	ProfileDAO pDao;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public careerDevData() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		ArrayList<CareerDev> list = new ArrayList<CareerDev>();
		Writer out = response.getWriter();
		String jsonString = "";
		
		/**
		 * cast data from database into json to present on Jqgrid in view
		 */
		
		try {
			if(!session.isNew()) {
				pDao = new ProfileDAO();
				Employee em = (Employee) session.getAttribute("person");
				list = pDao.listCareerDevOfAEmployee(em.getUserid());
				if(!list.isEmpty()) {
					int recNo = list.size();
					
					JSONArray cellArray = new JSONArray();
					
					for(CareerDev caDev : list) {
						JSONObject cellObj = new JSONObject();
						cellObj.put("id", caDev.getCareerDevId());
						cellObj.put("goal", caDev.getGoal());
						cellObj.put("action", caDev.getAction());
						cellObj.put("target", caDev.getTarget().toString());
						cellObj.put("complete", caDev.getComplete().toString());
						cellObj.put("comment", caDev.getComment());
						cellObj.put("status", caDev.getStatus());
						cellArray.put(cellObj);
					}
					
					jsonString = "{ \"page\": \"1\", \"record\": \"" + recNo + "\", \"rows\": ";
					jsonString += ( cellArray.toString() + " }"); 
					
					out.write(jsonString);
					out.flush();
				}
			}
			
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
